package cn.java79.quiz.web;

import cn.java79.quiz.entity.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
@WebListener//监听session对象的赋值
public class QuizListener implements HttpSessionAttributeListener {
    //登录的用户放入一个集合
    public static List<User> onlines=new ArrayList<>();
    //捕获setAttribute方法
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println(httpSessionBindingEvent.getSession().getId()+" 发生了set操作");
        String name = httpSessionBindingEvent.getName();
        if("STUDENT_LOGIN".equals(name)){
            User user = (User)httpSessionBindingEvent.getValue();
            onlines.add(user);
        }
    }
    //捕获removeAttribute方法
    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println(httpSessionBindingEvent.getSession().getId()+" 发生了删除操作");
        String name = httpSessionBindingEvent.getName();
        if("STUDENT_LOGIN".equals(name)){
            User user = (User)httpSessionBindingEvent.getValue();
           for(int i=onlines.size()-1;i>=0;i--){
               if(onlines.get(i).getId()==user.getId())
               {
                   onlines.remove(i);
                   return;
               }

           }
        }
    }

    //值被替换
    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        //>>>httpSessionBindingEvent.getSession()
    }
}
